package com.hn.shirojwt.component;

import com.hn.shirojwt.util.JwtTokenUtil;
import org.apache.shiro.web.filter.authc.FormAuthenticationFilter;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.PrintWriter;

/**
 * 自定义重写登录认证放方法
 * @author dnkj011
 *
 */
public class MyFormAuthenticationFilter extends FormAuthenticationFilter {
    JwtTokenUtil jwtTokenUtil = new JwtTokenUtil();

    private final String TOKENHEADER = "Authorization";

    @Override
    public boolean isAccessAllowed(ServletRequest request, ServletResponse response, Object mappedValue) {
    	HttpServletRequest request1 = (HttpServletRequest) request;
        //为了过滤跨域，先发送的那个请求
    	if (request1.getMethod().toUpperCase().equals("OPTIONS")) {
    		return true;
    	}
        try {
            String token = request1.getHeader(TOKENHEADER);
            return jwtTokenUtil.validateToken(token);
        } catch (Exception e) {
           return false;
        }
    }
    /**
     * 未登陆直接返回消息提示
     */
    @Override
    protected boolean onAccessDenied(ServletRequest request, ServletResponse response) throws Exception {
        HttpServletResponse res = (HttpServletResponse)response;
        res.setHeader("Access-Control-Allow-Origin", "*");
        res.setStatus(HttpServletResponse.SC_OK);
        res.setCharacterEncoding("UTF-8");
        PrintWriter writer = res.getWriter();
        //返回未登陆
        writer.write("未登录或token失效");
        writer.close();
        return false;
    }
}
